<?php

namespace app\admin\controller;

use think\Db;
use think\Validate;
class Subscribe extends Base{
	public function index(){
		return $this->fetch();
	}
	public function index_data(){
		$input = input();
		$where=[];
		if (isset($input['keywords']) and !empty($input['keywords'])) {
			$where[] = ['s.name|s.mobile','like', '%' . $input['keywords'] . '%'];
		}
		
		if (isset($input['seach_time']) and !empty($input['seach_time'])) {
			$str = explode('~',$input['seach_time']);
		    $star_time=$str[0]? $str[0] : '';
		    $end_time=$str[1] ? $str[1] : '';
			$where[]=['s.add_time','between',[strtotime($star_time),strtotime($end_time)+86400]];
		}
		$page       = ($input['page']-1)*$input['limit'];
		$limit      = $input['limit'];
		
		$data = Db::name('subscribe')->alias('s')
        ->join('user u','s.user_id=u.id','LEFT')//user_id 客户ID
		->field('s.*,u.mobile u_mobile')
		->where($where)
		->limit($page,$limit)
		->order('s.add_time desc')
		->select();
		
		foreach($data as $k=>$v){
			$baojia=Db::name('process')->where('status',2)->where('s_id',$v['id'])->where('t_id',5)->order('id desc')->find();
			$baojia1=Db::name('process')->where('s_id',$v['id'])->where('t_id',6)->order('id desc')->find();
			$offer_info=Db::name('offer')->where('s_id',$v['id'])->field('id,status')->order('id desc')->find();
			$data[$k]['is_baojia'] = [];
			if(!empty($baojia)){
				$data[$k]['is_baojia'] = 1;
			}
			if(!empty($baojia1)){
				$data[$k]['is_baojia'] = 0;
			}
			$data[$k]['offer_info'] = [];
			if($offer_info){
				$data[$k]['offer_info'] = $offer_info;
			}
			$staff_type_name_arry=Db::name('staff_type')->where('id','in',$v['item_ids'])->column('name');
			$data[$k]['staff_type_name']=implode(',', $staff_type_name_arry);
			
			// 测量或者报价
			if($v['is_allot'] == 0){
				// 测量或者报价
				$ce = Db::name('process')->alias('p')
				->join('staff_type s','s.id=p.t_id','LEFT')//user_id 客户ID
				->where('p.user_id',$v['allot_id'])
				->where('p.s_id',$v['id'])
				->field('s.name s_name')
				->order('p.id desc')
				->find();
				$jindu = $ce['s_name'];
			}else{
				// 指给团队
				$jindu = Db::name('team')->where('id',$v['allot_id'])->value('nickname');
				
			}
			$data[$k]['jindu_name']=$jindu;
		}
		$count = Db::name('subscribe')
		->alias('s')
		->join('user u','s.user_id=u.id','LEFT')
		->where($where)
		->count();
		
		return hSuccess('OK', $data,$count,ceil($count/$limit));
	}
	public function add(){
		if($this->request->isPost()) {
			//是提交操作
			$post = $this->request->post();
			
			$rule = [
			    'username'   => 'require',
			    'mobile' => 'require',
			];
			$msg = [
			    'username.require'  => '名称不能为空',
			    'mobile.require'  	=> '手机不能为空',
			];
			
			$validate   = Validate::make($rule,$msg);
		    //验证部分数据合法性
		    if (!$validate->check($post)) {
		        $this->error('提交失败：' . $validate->getError());
			}
			$data = [
				'is_grade'		=>	intval($post['is_grade']),
				'user_id'		=>	$post['user_id'],
				'name'			=>	$post['username'],
				'mobile'		=>	$post['mobile'],
				'address'		=>	$post['address'],
				'item_ids'		=>	implode(',', $post['item_ids']),
				'remark'		=>	$post['remark'],
				'order'			=>	get_order(),
				'add_time'		=>	time(),
			];
			$res = Db::name('subscribe')->insert($data);
		    if($res) {
		    	return hSuccess('操作成功');
		    } else {
				return hError(302,'操作失败');
		    }
		}
		$xiang = Db::name('staff_type')->where('status',1)->order('sort asc')->select();
		$this->assign('xiang',$xiang);
		$user = Db::name('user')->where('identity',1)->order('id asc')->field('id,username,mobile')->select();
		$this->assign('user',$user);
		return $this->fetch();
	}
	// 接收
	public function receive(){
		
		if($this->request->isPost()) {
			//是提交操作
			$post = $this->request->post();
			if(Db::name('user')->where('staff_type',5)->find($post['celiang'])){
				// var_dump($post);die;
				Db::startTrans();
				try {
					// 1修改数据
					$up_res = Db::name('subscribe')->where('id',$post['id'])->update(['status'=>1,'update_time'=>time(),'is_allot'=>0,'allot_id'=>$post['celiang']]);
					if(!$up_res){
						Db::rollback();
					}
					// 2项目插入数据
					$process_data = [
						'user_id'=>$post['celiang'],
						't_id'=>5,
						's_id'=>$post['id'],
						'add_time'=>time()
					];
					$in_res = Db::name('process')->insert($process_data);
					if(!$in_res){
						Db::rollback();
					}
				    Db::commit();
					return hSuccess('操作成功');
				} catch (\Exception $e) {
				    Db::rollback();
				}
			}else{
				return hError(302,'测量人员不存在！');
			}
			
		}
		$zhipai = Db::name('user')->where('staff_type',5)->field('id,username')->select();
		$this->assign('zhipai',$zhipai);
		
		$id = input('id');
		$this->assign('id',$id);
		return $this->fetch();
	}	
	public function speed(){
		$id = input('id');
		$info = Db::name('process')->alias('p')
		->join('subscribe s','p.s_id=s.id','LEFT')
        ->join('user u','p.user_id=u.id','LEFT')
        ->join('staff_type t','u.staff_type=t.id','LEFT')
		->field('p.*,u.username u_name,t.name t_name,s.name s_name,FROM_UNIXTIME(p.add_time,"%Y-%m-%d %H:%i:%s") as  add_time')
		->where('p.s_id',$id)
		->order('p.status asc')
		->select();
		foreach($info as $k=>$v){
			switch ($v['status'])
			{
				case 0:
					$status_name = '待确定';
					break;
				case 1:
					$status_name = '已确定';
					break;
				case 2:
					$status_name = '已完成';
					break;
				case 3:
					$status_name = '已关闭';
					break;
				case 4:
					$status_name = '官方驳回';
					break;
				case 5:
					$status_name = '客户驳回';
					break;
				default:
				    $status_name = '待确定';
				    break;
			}
			$info[$k]['status_name'] = $status_name;
		}
		$this->assign('info',$info);
		return $this->fetch();
	}
	public function offer(){
		if($this->request->isPost()) {
			//是提交操作
			$post = $this->request->post();
			$status = $post['status'];

			Db::startTrans();
			try {
				if($status==1){
					// 审核通过操作
					$up_res1 = Db::name('offer')->where('id',$post['id'])->update(['status'=>2,'update_time'=>time()]);
					
					if(!$up_res1){
						Db::rollback();
						return hError(302,'审核失败');
					}
					// 1修改数据
					$up_res2 = Db::name('subscribe')->where('id',$post['s_id'])->update(['status'=>3,'update_time'=>time()]);
					if(!$up_res2){
						Db::rollback();
					}
				}else{
					// 审核失败
					$up_res3 = Db::name('offer')->where('id',$post['id'])->update(['status'=>3,'update_time'=>time(),'reason'=>$post['examine_msg']]);
					
					if(!$up_res3){
						Db::rollback();
						return hError(302,'审核失败');
					}
					$up_res4 = Db::name('subscribe')->where('id',$post['s_id'])->update(['status'=>1,'update_time'=>time()]);
					if(!$up_res4){
						Db::rollback();
					}
					
				}
				
				// // 2项目插入数据
				// $process_data = [
				// 	'user_id'=>$post['celiang'],
				// 	't_id'=>5,
				// 	's_id'=>$post['id'],
				// 	'add_time'=>time()
				// ];
				// $in_res = Db::name('process')->insert($process_data);
				// if(!$in_res){
				// 	Db::rollback();
				// }
				Db::commit();
				return hSuccess('操作成功');
			} catch (\Exception $e) {
				Db::rollback();
			}
		}
		$id = input('id');
		
		$subscribe_info= Db::name('subscribe')->where('id',$id)->find();
		
		$staff_type_name_arry=Db::name('staff_type')->where('id','in',$subscribe_info['item_ids'])->column('name');
		
		$process_info= Db::name('process')->where('status','<>',3)->where(['s_id'=>$id,'t_id'=>5])->order('id desc')->field('id,visit_time')->find();
		// var_dump($process_info);die;
		$offer_info = Db::name('offer')->where(['s_id'=>$id,'status'=>1])->order('id desc')->find();
		
		$file_data_info=Db::name('file_data')->where(['p_id'=>$process_info['id']])->order('id desc')->find();
		
		$data=[
			'id'=>$id,
			'o_id'=>$offer_info['id'],
			's_order'=>$subscribe_info['order'],
			'visit_time'=>$process_info['visit_time'],
			'mianji'=>$offer_info['mianji'],
			'huxing'=>$offer_info['huxing'],
			'money'=>$offer_info['money'],
			'reason'=>$subscribe_info['remark'],
			'staff_type_name'=>implode(',', $staff_type_name_arry),
			'info'=>$file_data_info['file_src']
		];
		// var_dump($file_data_info);die;
		$this->assign('info',$data);
		return $this->fetch();
	}
	public function yuyue_info(){
		
		$id = input('id');
		
		$subscribe_info= Db::name('subscribe')->where('id',$id)->find();
		
		$staff_type_name_arry=Db::name('staff_type')->where('id','in',$subscribe_info['item_ids'])->column('name');
		
		$process_info= Db::name('process')->where('status','<>',3)->where(['s_id'=>$id,'t_id'=>5])->order('id desc')->field('id,visit_time')->find();
		// var_dump($process_info);die;
		$offer_info = Db::name('offer')->where(['s_id'=>$id,'status'=>1])->order('id desc')->find();
		
		$file_data_info=Db::name('file_data')->where(['p_id'=>$process_info['id']])->order('id desc')->find();
		
		$data=[
			'id'=>$id,
			'o_id'=>$offer_info['id'],
			's_order'=>$subscribe_info['order'],
			'visit_time'=>$process_info['visit_time'],
			'mianji'=>$offer_info['mianji'],
			'huxing'=>$offer_info['huxing'],
			'money'=>$offer_info['money'],
			'reason'=>$subscribe_info['remark'],
			'staff_type_name'=>implode(',', $staff_type_name_arry),
			'info'=>$file_data_info['file_src']
		];
		// var_dump($file_data_info);die;
		$this->assign('info',$data);
		return $this->fetch();
	}
	public function look_info(){
		
		$this->assign('id',input('id'));
		return $this->fetch();
	}
	// 接收
	public function baojia(){
		
		if($this->request->isPost()) {
			//是提交操作
			$post = $this->request->post();
			if(Db::name('user')->where('staff_type',6)->find($post['celiang'])){
				// var_dump($post);die;
				Db::startTrans();
				try {
					// 1修改数据
					$up_res = Db::name('subscribe')->where('id',$post['id'])->update(['update_time'=>time(),'allot_id'=>$post['celiang']]);
					if(!$up_res){
						Db::rollback();
					}
					// 2进度插入数据
					$process_data = [
						'user_id'=>$post['celiang'],
						't_id'=>6,
						'status'=>1,
						's_id'=>$post['id'],
						'add_time'=>time()
					];
					$in_res = Db::name('process')->insert($process_data);
					if(!$in_res){
						Db::rollback();
					}
				    Db::commit();
					return hSuccess('操作成功');
				} catch (\Exception $e) {
				    Db::rollback();
				}
			}else{
				return hError(302,'报价人员不存在！');
			}
			
		}
		$zhipai = Db::name('user')->alias('u')
        ->join('staff_type s','s.id=u.staff_type','LEFT')
		->where('u.staff_type',6)
		->field('u.id,u.username,s.name s_name')
		->select();
		$this->assign('zhipai',$zhipai);
		
		$id = input('id');
		$this->assign('id',$id);
		return $this->fetch();
	}
	
	public function z_team(){
		
		if($this->request->isPost()) {
			//是提交操作
			$post = $this->request->post();
			
			$team_info = Db::name('team')->where('id',$post['celiang'])->find();
			
			Db::startTrans();
			try {
				// 1修改数据
				$up_res = Db::name('subscribe')->where('id',$post['id'])->update(['update_time'=>time(),'is_allot'=>1,'x_status'=>1,'is_grade'=>1,'allot_id'=>$post['celiang']]);
				if(!$up_res){
					Db::rollback();
				}
				// 2项目插入数据
				$process_data = [
					'user_id'=>$team_info['t_id'],
					's_id'=>$post['id'],
					'team_id'=>$team_info['id'],
					'add_time'=>time()
				];
				$in_res = Db::name('process')->insert($process_data);
				if(!$in_res){
					Db::rollback();
				}
				Db::commit();
				return hSuccess('操作成功');
			} catch (\Exception $e) {
				Db::rollback();
			}
			
		}
		$zhipai = Db::name('team')
		->where('is_del',0)
		->field('id,nickname')
		->select();
		$this->assign('zhipai',$zhipai);
		
		$id = input('id');
		$this->assign('id',$id);
		return $this->fetch();
	}
	
	// 汇报记录
	public function report(){
		$id = input('id');
		$info = Db::name('report')->alias('r')
		->join('subscribe s','r.s_id=s.id','LEFT')
	    ->join('user u','r.user_id=u.id','LEFT')
	    ->join('report_type t','t.id=r.r_id','LEFT')
		->field('r.*,u.username u_name,t.name t_name,s.name s_name,FROM_UNIXTIME(r.add_time,"%Y-%m-%d %H:%i:%s") as  add_time')
		->where('r.s_id',$id)
		->select();
		
		$this->assign('info',$info);
		return $this->fetch();
	}
	// 汇报分类
	public function report_type(){
		return $this->fetch();
	}
	public function report_data(){
		$input = input();
		$where=[];
		if (isset($input['keywords']) and !empty($input['keywords'])) {
			$where[] = ['name','like', '%' . $input['keywords'] . '%'];
		}
		
		if (isset($input['seach_time']) and !empty($input['seach_time'])) {
			$str = explode('~',$input['seach_time']);
		    $star_time=$str[0]? $str[0] : '';
		    $end_time=$str[1] ? $str[1] : '';
			$where[]=['add_time','between',[strtotime($star_time),strtotime($end_time)+86400]];
		}
		$page       = ($input['page']-1)*$input['limit'];
		$limit      = $input['limit'];
		$data = Db::name('report_type')
		->where($where)
		->order('sort asc')
		->limit($page,$limit)
		->select();
		
		$count = Db::name('report_type')
		->where($where)
		->count();
		
		return hSuccess('OK', $data,$count,ceil($count/$limit));
	}
	public function report_add(){
		if($this->request->isPost()) {
			//是提交操作
			$post = $this->request->post();
			
			$rule = [
			    'name'   => 'require',
			];
			$msg = [
			    'name.require'  => '名称不能为空',
			];
			$validate   = Validate::make($rule,$msg);
		    //验证部分数据合法性
		    if (!$validate->check($post)) {
		        $this->error('提交失败：' . $validate->getError());
		    }
			$post['add_time'] 	= time();
			
			$res = Db::name('report_type')->insert($post);
		    if($res) {
		    	return hSuccess('操作成功');
		    } else {
				return hError(302,'操作失败');
		    }
		}
		
		return $this->fetch();
	}
	public function report_edit(){
		// 获取参数
		$param = $this->request->param();
		// 提交操作
		if($this->request->isAjax()){
			
			$data = [
				'name'		=>	$param['name'],
				'is_show'	=>	isset($param['is_show']) ?$param['is_show'] :0,
				'sort'	=>	$param['sort'],
				'update_time'	=>	time(),
			];
			
			$res = Db::name('report_type')->where('id',$param['id'])->update($data);
	        if($res){
	            return hSuccess('操作成功');
	        }else{
	            return hError('-1','操作失败');
	        }
		}
		// 展示界面
		$info = Db::name('report_type')->find($param['id']);
		$this->assign('info',$info);
	    return $this->fetch();
	}
	public function report_delete(){
		$input = $this->request->param();
		if($this->request->isAjax()) {
			$id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
			$res = Db::name('report_type')->where('id',$id)->delete();
			if($res) {
				return hSuccess('删除成功');
			} else {
				return hError(410,'删除失败');
			}
		}
	}
	
}
?>